'use strict';

import { customer_orderModel } from "../model/customer_order";
import { ServiceBase, Exceptions } from '../kalend';
import { merchanthistoryService } from "./merchanthistory";
import { common } from "../middleware/common";
import { usertokenService } from "./usertoken";
import { customer_accountService } from "./customer_account";
import { merchant_commentService } from "./merchant_comment";
import { merchant_wineService } from "./merchant_wine";
import { merchantService } from "./merchant";
import * as underscore from 'underscore';
var moment = require('moment');
import _ = require('underscore');
import { sms } from "../middleware/sms";
import { ObjectId } from "bson";

class Customer_orderService extends ServiceBase {
    constructor() {
        super(customer_orderModel)
    }
    async query(params: any) {
        const offset = params.offset || 1;
        const limit = params.limit || 10;
        const token = params.token;
        const type = params.type || 1;
        let filter: any = {
            ordertype: '买单',
            paystatus: 1
        };
        if (!token) {
            throw Exceptions.notoken();
        }
        filter.customerid = (await usertokenService.getToken(token)).userid;

        if (type == 2) {
            filter.conins = { $gt: 0 };
        }

        let data: any = await super.queryPagination(offset, limit, {
            filter: filter,
            select: 'conins money meal end_time updateTime merchantid',
            populateOptions: {
                path: 'merchantid',
                select: 'logoimage name'
            }
        });
        let orderids = _.pluck(data.rows, '_id');
        let comms = await merchant_commentService.queryItems({ orderid: { $in: orderids } });
        data.rows = data.rows.map((item: any) => {
            // switch (item.paystatus) {
            //     case 0:
            //         item.paystatus = '未支付';
            //         break;
            //     case 1:
            //         item.paystatus = '支付成功';
            //         break;
            //     case 2:
            //         item.paystatus = '已关闭';
            //         break;
            //     case 3:
            //         item.paystatus = '已撤销';
            //         break;
            //     case 4:
            //         item.paystatus = '支付中';
            //         break;
            //     case 9:
            //         item.paystatus = '支付失败';
            //         break;
            //     default:
            //         break;
            // }
            let comm = comms.findIndex((b) => {
                return b.orderid && b.orderid.toJSON() === item._id.toJSON();
            })
            if (comm >= 0) {
                item.evaluate = true;
            } else {
                item.evaluate = false;
            }
            if (item.end_time) {
                item.end_time = moment(item.end_time).format('YYYY-MM-DD HH:mm');
            } else {
                item.end_time = moment(item.updateTime).format('YYYY-MM-DD HH:mm');
            }
            delete item.updateTime;
            return item;
        });
        const countdata = await customer_orderModel.aggregate([
            {
                $match: filter
            },
            {
                $group: {
                    _id: "customerid",
                    meal: { $sum: "$meal" },
                    conins: { $sum: "$conins" },
                    count: {$sum:1}
                }
            }
        ]);
        if (countdata && countdata.length > 0) {
            data.totaltitle = `共计消费${countdata[0].count}笔，餐币抵扣${countdata[0].meal}个，酒币抵扣${countdata[0].conins}个。`;
        }
        return data;
    }
    async queryall(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const uid = params.uid;
        const mid = params.mid;
        const paystatus = params.paystatus;
        const starttime = params.starttime;
        const endtime = params.endtime;
        let filter: any = {};
        if (uid) {
            filter.customerid = uid;
        }
        if (mid) {
            filter.merchantid = mid;
        }
        if (paystatus !== 'all') {
            filter.paystatus = paystatus;
        }
        if (starttime) {
            filter.updateTime = { '$gte': new Date(moment(new Date(starttime)).format('YYYY-MM-DD') + '  00:00:00') };
        }
        if (endtime) {
            if (filter.updateTime) {
                filter.updateTime['$lte'] = new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59');
            } else {
                filter.updateTime = { '$lte': new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59') };
            }
        }
        let data: any = await super.queryPagination(offset, limit, {
            filter: filter,
            select: 'customerid merchantid conins code paystatus paytype end_time updateTime money meal person rate ratemoney agentrate agentreward',
            populateOptions: [
                {
                    path: 'customerid',
                    select: 'nickname'
                },
                {
                    path: 'merchantid',
                    select: 'name'
                }
            ]
        });
        let moneyTotal = 0;
        data.rows = data.rows.map((item: any) => {
            switch (item.paystatus) {
                case 0:
                    item.paystatus = '未支付';
                    break;
                case 1:
                    item.paystatus = '支付成功';
                    break;
                case 2:
                    item.paystatus = '已关闭';
                    break;
                case 3:
                    item.paystatus = '已撤销';
                    break;
                case 4:
                    item.paystatus = '支付中';
                    break;
                case 9:
                    item.paystatus = '支付失败';
                    break;
                default:
                    break;
            }
            if (item.end_time) {
                item.end_time = moment(item.end_time).format('YYYY-MM-DD HH:mm');
            } else {
                item.end_time = moment(item.updateTime).format('YYYY-MM-DD HH:mm');
            }
            if (item.customerid) {
                item.nickname = item.customerid.nickname;
            }
            if (item.merchantid) {
                item.mername = item.merchantid.name;
            } else {
                item.mername = '升级会员';
            }
            item.paytype = '微信支付';
            delete item.customerid;
            delete item.merchantid;
            delete item.updateTime;
            moneyTotal = common.add(moneyTotal, item.money || 0);
            return item;
        });

        // let moneyTotal = eval(_.pluck(data.rows, 'money').join('+')) || 0;
        let coninsTotal = eval(_.pluck(data.rows, 'conins').join('+')) || 0;
        data.footTotal = `共计 ${moneyTotal} 元，酒币 ${coninsTotal} 个`;
        return data;
    }
    async buildorder(mid: any, uid: any, money: number, conins: number, person: number, winelist: Array<any>, meal: number, openid: any, winemoney: number, mealmoney: number, ordertype?: any) {
        if (!ordertype && !mid) {
            throw Exceptions.known('未获取到商户信息，请重新进入买单页');
        }

        let doc: any = {
            openid: openid,
            paystatus: 0,
            code: common.buildCode(),// 生产订单编号
            money: money,
            winemoney: winemoney || 0,
            conins: conins,
            customerid: uid,
            merchantid: mid,
            person: person,
            winelist: winelist,
            meal: meal,
            mealmoney: mealmoney || 0
        };
        let coninscount = 0;
        winelist.forEach((a) => {
            coninscount += a.count;
        });
        doc.coninscount = coninscount;
        if (ordertype) {
            doc.ordertype = ordertype;
        }

        if (ordertype === '买单') {
            let getmoney = doc.money;
            if (winemoney && winemoney > 0) {
                getmoney = common.sub(doc.money, winemoney);
            }
            /** 平台抽取餐费的可变佣金比例 */
            let merdata = await merchantService.querySingle({ _id: mid }, { select: 'rate' });
            if (merdata.rate && merdata.rate > 0) {
                doc.rate = merdata.rate;
                doc.ratemoney = common.div(common.mul(getmoney, doc.rate), 100);
                console.log(`生成订单：此次餐费支付【${getmoney}】元，平台佣金比例【${doc.rate}％】，订单成功平台将抽取佣金【${doc.ratemoney}】元`);

                // 平台抽取餐币佣金
                if (doc.meal && doc.meal > 0) {
                    doc.ratemeal = common.div(common.mul(doc.meal, doc.rate), 100);
                    console.log(`生成订单：此次餐币抵扣【${doc.meal}】个，平台佣金比例【${doc.rate}％】，订单成功平台将抽取餐币佣金【${doc.ratemeal}】元`);
                }
            } else {
                console.log('生成订单：未获取到抽取商户佣金比例，订单成功将不抽取佣金');
            }
            /** 大使奖励实际支付金额的千分之五 */
            //if (merdata.agentrate && merdata.agentrate > 0) {
            doc.agentrate = 5;
            doc.agentreward = common.div(common.mul(doc.money, 5), 1000);
            // if (doc.meal > 0) {
            //     let mealadd = common.div(common.mul(doc.meal, merdata.agentrate), 1000);
            //     doc.agentreward = common.add(doc.agentreward, mealadd);
            // }
            console.log(`生成订单：此次实际支付【${money}】元，宣传大使奖励比例【5‰】，订单成功大使将奖励佣金【${doc.agentreward}】元`);
            // } else {
            //     console.log('生成订单：未获取到宣传大使佣金比例，订单成功将不奖励佣金');
            // }
        }

        let res = await this.create(doc);
        return res.code;
    }
    // 更新订单状态
    async updateOrder(ordercode: any, info: any) {
        const orderdata = await this.querySingle({ code: ordercode, paystatus: 0 });
        if (orderdata) {
            await this.update(orderdata._id, {
                total_fee: info.total_fee,
                paytype: info.trade_type,
                paystatus: 1,
                wxorderid: info.transaction_id,
                time_end: info.time_end,
                order_info: info,
            });
        }
        else {
            console.log('未找到对应订单记录' + ordercode);
            let doc: any = {
                code: ordercode,
                total_fee: info.total_fee,
                money: common.div(info.total_fee, 100),
                merchantid: info.mch_id,
                openid: info.openid,
                paytype: info.trade_type,
                paystatus: 1,
                wxorderid: info.transaction_id,
                end_time: info.end_time,
                order_info: info,
                isaddnew: true
            };
            await this.create(doc);
        }



        // 更新入驻商户账户余额和酒币余额及记录消费记录
        if (orderdata.merchantid && orderdata.ordertype === '买单') {
            /** 给商家发短信通知 */
            this.sendMerchSMS(orderdata);
            console.log('买单：准备增加商户余额、餐币余额，扣减商户酒币');
            merchanthistoryService.buildhistory(orderdata);
            // 更新酒库存
            if (orderdata.winelist && orderdata.winelist.length > 0) {
                console.log('买单：准备更新酒水库存');
                merchant_wineService.updatewinestock({ mid: orderdata.merchantid, wines: orderdata.winelist });
            }
        }

        // 升级会员
        if (orderdata.ordertype == '升级会员' || orderdata.ordertype == '升级白金会员' || orderdata.ordertype == '升级钻石会员') {
            console.log('升级会员成功');
            customer_accountService.upvipsuccess(orderdata);
        }
    }

    // 金额为0
    async successOrder(ordercode: any) {
        const orderdata = await this.querySingle({ code: ordercode, paystatus: 0 });
        if (orderdata) {
            await this.update(orderdata._id, {
                paystatus: 1,
                time_end: new Date()
            });
        }
        else {
            console.log('未找到对应订单记录' + ordercode);
            let doc: any = {
                code: ordercode,
                paystatus: 1,
                end_time: new Date(),
                isaddnew: true
            };
            await this.create(doc);
        }
        // 更新入住商户账户余额和酒币余额及记录消费记录
        if (orderdata.merchantid && orderdata.ordertype === '买单') {
            console.log('准备增加商户余额，扣减商户酒币、餐币');
            merchanthistoryService.buildhistory(orderdata);
            // 更新酒库存
            console.log('买单：准备更新酒水库存');
            if (orderdata.winelist && orderdata.winelist.length > 0) {
                console.log('买单：准备更新酒水库存');
                merchant_wineService.updatewinestock({ mid: orderdata.merchantid, wines: orderdata.winelist });
            }
        }
    }

    //根据商户id查询商户订单
    async querybymid(params: any) {
        const offset = params.offset;
        const limit = params.limit;

        const paystatus = params.paystatus;

        const starttime = params.starttime;
        const endtime = params.endtime;
        let filter: any = {};

        let merchants: any = await merchantService.queryByUserId({
            offset: params.offset, limit: params.limit,
            userid: params.userid
        });

        let ids = underscore.pluck(merchants.rows, '_id')


        filter.merchantid = { '$in': ids };;
        if (paystatus) {
            filter.paystatus = paystatus;
        }

        if (starttime) {
            filter.updateTime = { '$gte': new Date(moment(new Date(starttime)).format('YYYY-MM-DD') + '  00:00:00') };
        }
        if (endtime) {
            if (filter.updateTime) {
                filter.updateTime['$lte'] = new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59');
            } else {
                filter.updateTime = { '$lte': new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59') };
            }
        }

        let data = await super.queryPagination(offset, limit, {
            filter: filter,
            select: 'customerid merchantid conins money code paystatus paytype end_time updateTime',
            populateOptions: [
                {
                    path: 'customerid',
                    select: 'name'
                },
                {
                    path: 'merchantid',
                    select: 'name'
                }
            ]
        });
        data.rows = data.rows.map((item) => {
            switch (item.paystatus) {
                case 0:
                    item.paystatus = '未支付';
                    break;
                case 1:
                    item.paystatus = '支付成功';
                    break;
                case 2:
                    item.paystatus = '已关闭';
                    break;
                case 3:
                    item.paystatus = '已撤销';
                    break;
                case 4:
                    item.paystatus = '支付中';
                    break;
                case 9:
                    item.paystatus = '支付失败';
                    break;
                default:
                    break;
            }
            if (item.end_time) {
                item.end_time = moment(item.end_time).format('YYYY-MM-DD HH:mm');
            } else {
                item.end_time = moment(item.updateTime).format('YYYY-MM-DD HH:mm');
            }
            if (item.customerid) {
                item.cusname = item.customerid.name;
            }
            if (item.merchantid) {
                item.mername = item.merchantid.name;
            }
            delete item.customerid;
            delete item.merchantid;
            delete item.updateTime;
            return item;
        });
        return data;
    }

    //根据商户id查询商户订单
    async querybymerchantid(params: any) {
        const offset = params.offset;
        const limit = params.limit;

        const paystatus = params.paystatus;

        const starttime = params.starttime;
        const endtime = params.endtime;
        let filter: any = {};

        // let merchants: any = await merchantService.queryByUserId({
        //     offset: params.offset, limit: params.limit,
        //     userid: params.userid
        // });

        // let ids = underscore.pluck(merchants.rows, '_id')


        filter.merchantid = params.mid;;
        if (paystatus) {
            filter.paystatus = paystatus;
        }

        if (starttime) {
            filter.updateTime = { '$gte': new Date(moment(new Date(starttime)).format('YYYY-MM-DD') + '  00:00:00') };
        }
        if (endtime) {
            if (filter.updateTime) {
                filter.updateTime['$lte'] = new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59');
            } else {
                filter.updateTime = { '$lte': new Date(moment(endtime).format('YYYY-MM-DD') + '  23:59:59') };
            }
        }

        let data = await super.queryPagination(offset, limit, {
            filter: filter,
            select: 'customerid merchantid conins money code paystatus paytype end_time updateTime',
            populateOptions: [
                {
                    path: 'customerid',
                    select: 'name'
                },
                {
                    path: 'merchantid',
                    select: 'name'
                }
            ]
        });
        data.rows = data.rows.map((item) => {
            switch (item.paystatus) {
                case 0:
                    item.paystatus = '未支付';
                    break;
                case 1:
                    item.paystatus = '支付成功';
                    break;
                case 2:
                    item.paystatus = '已关闭';
                    break;
                case 3:
                    item.paystatus = '已撤销';
                    break;
                case 4:
                    item.paystatus = '支付中';
                    break;
                case 9:
                    item.paystatus = '支付失败';
                    break;
                default:
                    break;
            }
            if (item.end_time) {
                item.end_time = moment(item.end_time).format('YYYY-MM-DD HH:mm');
            } else {
                item.end_time = moment(item.updateTime).format('YYYY-MM-DD HH:mm');
            }
            if (item.customerid) {
                item.cusname = item.customerid.name;
            }
            if (item.merchantid) {
                item.mername = item.merchantid.name;
            }
            delete item.customerid;
            delete item.merchantid;
            delete item.updateTime;
            return item;
        });
        return data;
    }

    //计算商户平台抽成比例
    async calcmerchantrate(params: any) {
        const merchantid: any = params.mid;

        //总共就餐人数
        let merchantTotalPerson: any = 0;
        //总收入
        let merchantOrderTotalMoney: any = 0;

        //查询商户所有订单
        let orders: any = await this.queryAll({ filter: { merchantid: merchantid } });
        for (let index = 0; index < orders.length; index++) {
            const element = orders[index];
            merchantTotalPerson = merchantTotalPerson + element.person;
            merchantOrderTotalMoney = merchantOrderTotalMoney + element.money;
        }

        if (merchantTotalPerson == 0 || merchantOrderTotalMoney) {
            //默认比例
            return { merchantrate: 10 }
        }
        //人均消费总额
        let rjmoney = merchantOrderTotalMoney / merchantTotalPerson;
        let merchantrate = 0;
        if (rjmoney >= 40 && rjmoney < 45) {
            merchantrate = 13;
        }

        if (rjmoney >= 45 && rjmoney < 50) {
            merchantrate = 12;
        }

        if (rjmoney >= 50 && rjmoney < 55) {
            merchantrate = 11;
        }

        if (rjmoney >= 55 && rjmoney < 60) {
            merchantrate = 10;
        }

        if (rjmoney >= 60 && rjmoney < 65) {
            merchantrate = 9.5;
        }

        if (rjmoney >= 65 && rjmoney < 70) {
            merchantrate = 9;
        }

        if (rjmoney >= 70 && rjmoney < 75) {
            merchantrate = 8.5;
        }

        if (rjmoney >= 75 && rjmoney < 80) {
            merchantrate = 8;
        }
        if (rjmoney >= 80 && rjmoney < 85) {
            merchantrate = 7.5;
        }
        if (rjmoney >= 85) {
            merchantrate = 7;
        }
        return { merchantrate: merchantrate }
    }

    async queryAlls(filter: any) {
        return this.queryAll({
            filter: filter
        });
    }
    async sendMerchSMS(orderdata: any) {
        const merchant = await merchantService.querySingle({ _id: orderdata.merchantid },
            {
                select: 'legalpersontel legaluserid name',
                populateOptions: {
                    path: 'legaluserid',
                    select: 'phone'
                }
            }
        );
        const phone = merchant.legaluserid.phone;
        const merchantname = merchant.name;
        let customername = '';
        const cus = await customer_accountService.querySingle({ _id: orderdata.customerid }, { select: 'nickname phone' });
        if (cus) {
            if (cus.nickname) {
                customername += cus.nickname;
            }
            if (cus.phone) {
                customername += '尾号(' + cus.phone.substring(7) + ')';
            }
        }
        customername = '[' + customername + ']';
        const paytime = moment(orderdata.time_end, 'yyyy-MM-dd HH:mm:ss');
        const paymoney = orderdata.money;
        let paydetail = '';
        if (orderdata.winemoney > 0) {
            paydetail += ',酒费( ' + orderdata.winemoney + ' 元)';
        }
        if (orderdata.mealmoney > 0) {
            paydetail += ',餐费( ' + orderdata.mealmoney + ' 元)';
        }
        paydetail = paydetail.substr(1, paydetail.length);
        const winelist: Array<any> = orderdata.winelist.map((a: any) => {
            a.wineid = new ObjectId(a._id);
            return a;
        });
        const wineids = _.pluck(winelist, 'wineid');
        const winenames = await merchant_wineService.queralls({ _id: { $in: wineids } }, 'winename', { order: 1 });
        if (winenames.length > 0) {
            paydetail += ',酒水消费清单：'
        }
        let winedetail = '';
        winenames.forEach((item) => {
            const aa = winelist.find((a) => {
                return a._id === item._id.toJSON();
            });
            if (aa) {
                winedetail += `,${item.winename}(${aa.count}瓶)`;
            }
        });
        if (winenames.length > 0) {
            paydetail += winedetail.substr(1, winedetail.length) + '。';
        }
        console.log(`餐厅订单支付提醒短信：${phone}--尊敬的${merchantname},顾客${customername}于${paytime}消费金额${paymoney}.消费详情${paydetail}`);
        sms.sendmsg3(phone, merchantname, customername, paytime, paymoney, paydetail);
    }
}

export const customer_orderService = new Customer_orderService();